
	// H5 plus事件处理
  function appplus(callback) {
		if(window.plus) {
			setTimeout(function() { //解决callback与plusready事件的执行时机问题(典型案例:showWaiting,closeWaiting)
				callback();
			}, 0);
		} else {
			document.addEventListener("plusready", function() {
				callback();
			}, false);
		}
		return this;
	};
 
		/*初始化*/
		window.onload=function(){
			//取消浏览器的所有事件，使得active的样式在手机上正常生效
			document.addEventListener('touchstart',function(){
			    return false;
			},true);
			// 禁止选择
			document.oncontextmenu=function(){
				return false;
			};
			// H5 plus事件处理
//		 document.addEventListener('plusready', plusReady, false);
		 
		 appplus(function(){
			console.log('化初始:所有plus api都应该在此事件发生后调用，否则会出现plus is undefined');
		 	plusready();
		 });
			function plusready()
			{
				// 隐藏滚动条
				plus.webview.currentWebview().setStyle({
					scrollIndicator: 'none'
				});
			}
			
			// DOMContentLoaded事件处理
			var _domReady=false;
			document.addEventListener('DOMContentLoaded',function(){
				_domReady=true;
				compatibleAdjust();
			},false);
			// 兼容性样式调整
			var _adjust=false;
			function compatibleAdjust(){
				if(_adjust||!window.plus||!_domReady){
					return;
				}
				_adjust=true;
				// iOS平台特效
				if('iOS'==plus.os.name){
					document.getElementById('content').className='scontent';	// 使用div的滚动条
					if(navigator.userAgent.indexOf('StreamApp')>=0){	// 在流应用模式下显示返回按钮
						document.getElementById('back').style.visibility='visible';
					}
				}
				// 预创建二级窗口
			//	preateWebviews();
				// 关闭启动界面
					plus.navigator.setStatusBarBackground('#D74B28');
				setTimeout(function(){
					plus.navigator.closeSplashscreen();
				},200);
			}		 
		}	
		/* 初始化結束*/


angular.module('starter', ["ionic", "starter.service", "starter.filter", "ngCordova"])

.run(function($ionicPlatform,$cordovaStatusbar) {
  $ionicPlatform.ready(function() {
	    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
	      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
	      cordova.plugins.Keyboard.disableScroll(true);
	
	    }
	    ionic.Platform.fullScreen();
	    ionic.Platform.fullScreen(true,true);
	    if (window.StatusBar) {
	    	StatusBar.show();  // 状态栏显示  
//	      StatusBar.styleDefault();
	      $cordovaStatusbar.styleColor('transparent');
//	      $cordovaStatusbar.styleHex('#FAFAFA');
	    }
	});
})
.config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider, $httpProvider) {
	
//	$ionicConfigProvider.platform.ios.tabs.style('standard');
//$ionicConfigProvider.platform.ios.tabs.position('bottom');
//$ionicConfigProvider.platform.android.tabs.style('standard');
//$ionicConfigProvider.platform.android.tabs.position('bottom');
    
	$ionicConfigProvider.backButton.text("返回");
	$ionicConfigProvider.backButton.previousTitleText(false);
		
// 	$ionicConfigProvider.platform.ios.backButton.text(false);//隐藏返回按钮文字
// 	$ionicConfigProvider.platform.android.backButton.text(false);//隐藏返回按钮文字
// 	$ionicConfigProvider.platform.ios.backButton.previousTitleText(false);//隐藏返回按钮文字
// 	$ionicConfigProvider.platform.android.backButton.previousTitleText(false);//隐藏返回按钮文字
 		
  $ionicConfigProvider.platform.ios.navBar.alignTitle('center');
	$ionicConfigProvider.platform.android.navBar.alignTitle('center');
    
  $ionicConfigProvider.platform.ios.views.transition('ios');
	$ionicConfigProvider.platform.android.views.transition('android');
	
    // 添加拦截器
	$httpProvider.interceptors.push('authInterceptorService');

	$stateProvider
	
	.state('home',{
		url: '/home',
		templateUrl: 'template/home.html',
		controller: 'homeCtrl',
		cache: true
	})
    .state('userLogin', {
        url: '/userLogin',
        templateUrl: 'template/user_login.html',
        controller: 'userLoginCtrl'
    })
	.state('search',{
		url:'search',
		templateUrl:'template/search.html',
		controller: 'searchCtrl',
		cache:false
	})
    
    //带参跳转到科室选择
	.state('selectOffice', {
	    params: { 'hopId': null,"hopName":null,"addr":null },
	    url: 'selectOffice',
	    cache: false,
		templateUrl:'template/select_office.html',
		controller:'selectOfficeCtrl'
	})
	.state('selectHospital',{
		url:'selectHospital',
		templateUrl:'template/select_hospital.html',
		controller: 'selectHospitalCtrl',
		cache: false
		
	})
	.state('selectDoctors',{
	    url: 'selectDoctors',
	    params: { deId: null,deName:null },
	    cache: false,
		templateUrl:'template/select_doctors.html',
		controller:'selectDoctorsCtrl'
	})
	.state('doctorHome', {
	    params: { docId: null, detpId:null},
		url:'doctorHome',
		templateUrl:'template/doctor_home.html',
		controller: 'doctorHomeCtrl',
		cache: true
	})
	.state('remarks',{
	    params: { DoctorParma:null,type:null },
		url:'remarks',
		templateUrl:'template/remarks.html',
		controller: 'remarksCtrl',
		cache: true
	})
	
	.state('placeOrder', {
	    params: { doctorParma: null, regDate: null,treatFee:null,type:null, regFee: null, scheduleType: null, regTime:null,tempData:null },
		url:'placeOrder',
		templateUrl:'template/place_order.html',
		controller: 'placeOrderCtrl',
		cache: false
	})
	.state('paymentRoute', {
	    params: { reInfo: {} },
		url:'paymentRoute',
		templateUrl:'template/payment.html',
		controller: 'paymentCtrl',
	    cache:true
	})
	.state('payment_methodRoute',{
		url:'payment_methodRoute',
		templateUrl:'template/payment_method.html',
		controller: 'payment_methodCtrl',
		cache:false
	})
      //
    .state('selectArea', {
        url: 'selectArea',
        cache: false,
        params: { 'saveUrl': null },
        templateUrl: 'template/select_area.html',
        controller: 'selectAreaCtrl'
    })
	.state('userSet', {
	    url: 'userSet',
	    templateUrl: 'template/user_set.html',
	    controller: 'userSetCtrl'
	})
 
    ;
	
	$urlRouterProvider.otherwise("home");
})

//全局变量设置
.constant('ngAuthSettings', {
    apiServiceBaseUrl:'http://micholehao.xicp.net/',//'http://192.168.1.65:4998/',//数据接口地址
    clientId: '20171010', //appid
    clientSecret: 'password'//apppwd
})

//全局apiurl变量设置
.constant('appWebApi', {
    //app登录接口
    appLogin: "", 
    //app获取医院列表
    appGetHospital: "api/hospital/getlist",
    //获取省市
    getAreaCode: "api/common/getAreaCode",
    //关键字模糊搜索
    getSearchData: "api/common/getSearchData",
    //获取推荐医生
    getHotDoctor: "api/doctor/getHotDoctor",
    //获取科室医生
    getDeDoctor: "api/doctor/getDrRegInfo",
    //获取科室
    getDepartment: "api/hospital/getDeptRegInfo",
    //获取医生内业
    getDoctorHome: "api/doctor/getDrRegScheduleInfo",
    //提交预约订单
    addPreRegOrder: "api/hospital/addPreRegOrder",
    //当天预约锁住号源
    lockRegSeqToday: "api/hospital/lockRegSeqToday",
    //取消预约的订单
    cancelPreRegOrder: "api/hospital/cancelPreRegOrder",
    //解除锁定的号源
    unlockRegSeqToday: "api/hospital/unlockRegSeqToday",
    //获取类似的医生
    getLikeDoctor: "api/doctor/getLikeDoctor",
    //当天预约支付
    RegOrderToday:"api/hospital/addRegOrder",
    //取消预约支付的订单
    refundPreReg: "api/hospital/refundPreReg",
    //支付订单生成地址
    payment:"app/pay/getpayinfo?paytype="
})

 //全局可变的变量
.value("appBase", {
    cityCode: "0000",
    cityName: "全部",
    hospitalCode: "",
    hospitalName: "",
    //医院地址
    addr: ""
})

//post参数工厂
.factory('CountDown', function () {
    var data ={};
    var _countValue = 0;
    var _setCount=function(v)
    {
        if (_countValue > 1)
        {
            return;
        }
        _countValue = v;
        _open();
    };
    var _getValue = function () {
        return _countValue;
    };
    var _clear = function ()
    {
        _countValue = 0;
    };
    var _open=function ()
        {
            var t = setInterval(function () {
                if (_countValue > 0) {
                    _countValue = _countValue - 1;
                } else {
                    clearInterval(t);
                    return;
                }
            }, 1000)
        }
    
    data.CountValue = _getValue;
    data.SetCount = _setCount;
    data.clear = _clear;
    data.Open = _open;

    return data;
})


 //列表处理
.factory('Contacts', function () {
    var persons = {
        list: [
        [], [], [], [], [], [], [], [], [], [], [], [], [],
        [], [], [], [], [], [], [], [], [], [], [], [], []
        ],
        arrayLength: function (index) {
            return list[index].length;
        },
        clearEmpty: function () {
            for (var i = 0; i < persons.list.length; i++) {
                persons.list[i] = [];
            }
        }
    }
    return persons;
})

//绑定服务的事件
.factory('EventService', function () {
    var onEventFunc = {};
    return {
        on: function (type, f) {
            // 事件绑定
            onEventFunc[type] = f
        },
        trigger: function (type, data) {
            // 触发事件
            for (var item in onEventFunc) {
                if (item == type) {
                    onEventFunc[item](data);
                }
            }
        }
    };
})

//=========本地存储数据服务============
.factory('locals', ['$window', function ($window) {
    return {        //存储单个属性
        set: function (key, value) {
            $window.localStorage[key] = value;
        },        //读取单个属性
        get: function (key, defaultValue) {
            return $window.localStorage[key] || defaultValue;
        },        //存储对象，以JSON格式存储
        setObject: function (key, value) {
            $window.localStorage[key] = JSON.stringify(value);//将对象以字符串保存
        },        //读取对象
        getObject: function (key) {
            return JSON.parse($window.localStorage[key] || '{}');//获取字符串并解析成对象
        },
        clearKey: function (key)
        {
            //清理单个
           $window.localStorage.removeItem(Key);
        },
        clear:function(key)
        {
            //清理全部
            $window.localStorage.clear();
        }
    }
}])

  //本地登录的对象
.factory('UserInfo', function () {
    return {
        UserName: "用户名",
        DisplayName: "显示名字",
        patName:"",
        PicUrl: "",//头像
        Tel: "",//手机
        hisCardNumber: "",
        idCard:"",
        IsExpired: false, // 账号是否过期
        CheckedHsp: [],    // 选中的医院
        LoadTime:new Date().toDateString()//登录事件
    };
    //var userData = angular.fromJson(localStorage.getItem('user'));
})

//post参数工厂
.factory('ParData', function () {
    var data ={};
        data.name = "";//关键字
        data.cityCode = "";//城市code
        data.page = 10;//每页多少行
        data.currentPage = 1;//第几页
        data.sortType = "0";//排序类型
        data.isHot = 0;//是否推荐1是0否
        data.hospitalCode = "";
        data.deptId="";
        data.doctorId="";
        data.beginDate=null;
        data.endDate = null;
  
        data.clear=function()
        {
            var dateNow = new Date();
            var dateEnd = new Date();
            dateEnd.setDate(dateEnd.getDate()+5)
            data.name = "",//关键字
            data.cityCode = "",//城市code
            data.page = 10,//每页多少行
            data.currentPage = 1,//第几页
            data.sortType = "0",//排序类型
            data.isHot = 0,
            data.hospitalCode = ""
            data.deptId = "";
            data.doctorId = "";
            data.beginDate = dateNow.Format("yyyy-MM-dd");
            data.endDate = dateEnd.Format("yyyy-MM-dd");
        }

    return data;
})

.factory('searchData', function () {
    var data = [];
    data.keys = angular.fromJson(localStorage.getItem("searchDataSt"))||[];
    data.add = function (objstr) {
    	if(objstr==""||objstr==undefined)
    	{
    		return;
    	}
        if (data.keys.findIndex(x=>x.key == objstr) > -1)
        {
            return;
        }
        if (data.keys != null && data.keys.length > 7) {
            data.keys.shift();
        }  
        data.keys.push({ "key": objstr });
        localStorage.setItem("searchDataSt",angular.toJson(data.keys));
    };
    data.clear = function () {
        data.keys = [];
        localStorage.removeItem("searchDataSt");
    };
    return data;

})

